package proxy

import (
	"time"

	"gitee.com/fanshuaiself/sidecar/nacos"
	"github.com/nacos-group/nacos-sdk-go/model"
)

type discovery struct {
	services map[string]model.Service
	refreshInterval int 
	stopChan chan struct{}
}

var discoveryClient *discovery
func newDiscovery() *discovery {
	discoveryClient = &discovery{
		services: make(map[string]model.Service),
		refreshInterval: 30,
		stopChan: make(chan struct{}, 1),
	}
	return discoveryClient
}

func (d *discovery) Start() {
	go d.doDiscovery()
}

func (d *discovery) Stop() {
	d.stopChan <- struct{}{}
}

func (d *discovery) doDiscovery() {
	running := true
	for running {
		select {
		case <- d.stopChan:
			running = false
		case <- time.After(time.Duration(d.refreshInterval) * time.Second):
			d.refreshServices()
		}
	}
}

func (d *discovery) refreshServices() {
	services, err := nacos.GetAllServices()
	if err == nil {
		d.services = services
	}
}

func (d *discovery) getService(name string) (model.Service, bool) {
	service, ok := d.services[name]
	return service, ok 
}